package com.yoshino.leetcode.improve40.third;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        // 思路，排序，固定第一个数，另外两个数的和相当于 -res，转为两数求和
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; ) {
            int left = i + 1, right = nums.length - 1, target = -nums[i];
            while (left < right) {
                if (nums[left] + nums[right] == target) {
                    res.add(Arrays.asList(nums[left++], nums[right--], nums[i]));
                    while (left < right && nums[left] == nums[left - 1]) {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right + 1]) {
                        right--;
                    }
                } else if (nums[left] + nums[right] < target) {
                    left++;
                } else {
                    right--;
                }
            }
            // 避免重复
            i++;
            while (i < nums.length - 2 && nums[i] == nums[i - 1]) {
                i++;
            }
        }
        return res;
    }

    public int minSubArrayLen(int target, int[] nums) {
        // 思路：滑动窗口，双指针，每当 大于等于 左指针向右移动，直到小于
        int res = Integer.MAX_VALUE, left = 0, right = 0, sum = 0;
        while (right < nums.length) {
            sum += nums[right++];
            while (sum >= target) {
                res = Math.min(res, right - left);
                sum -= nums[left++];
            }
        }
        return res == Integer.MAX_VALUE ? 0 : res;
    }

    public int numSubarrayProductLessThanK(int[] nums, int k) {
        /**
         * 思路：存在 [A, B, C, D]
         *  A < K   -> count = A (0 - 0 + 1)
         *  AB < K  -> count = AB B (1 - 0 + 1)
         *  ABC > k -> BC < k   -> count = BC C (2 - 1 + 1)
         *          -> BC > k   -> C < k -> count = C (2 - 2 + 1)
         *  count = (right - left + 1)
         */
        int left = 0, right = 0, res = 1, count = 0;
        while (right < nums.length) {
            res *= nums[right];
            while (left <= right && res >= k) {
                res /= nums[left++];
            }
            if (left <= right) {
                count += right - left + 1;
            }
            right++;
        }
        return count;
    }
}